// pages/MyPage/MyInfo/MyInfo.js
const api = require("../../../config/api.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    customerInfo: {},
    ImgList:[],
  },

  onBack: function () {
    wx.navigateBack({
      delta: 1
    });
  },
  // 动态更新输入框数据
  onInputChange: function (e) {
    const field = e.currentTarget.dataset.field; // 获取字段名
    const value = e.detail.value; // 获取输入值
    this.setData({
      [`customerInfo.${field}`]: value // 动态更新嵌套字段
    });
  },
   // 上传管理人头像
   onUploadAvatar: function () {
    this.onUploadFile((uploadedUrl) => {
      // 设置头像的 URL
      this.setData({
        'customerInfo.customerUserHead': uploadedUrl
      });
    });
  },

  // 上传营业执照
  onUploadLicense: function () {
    this.onUploadFile((uploadedUrl) => {
      // 设置营业执照的 URL
      this.setData({
        'customerInfo.customerLicense': uploadedUrl
      });
    });
  },
  // 通用文件上传函数
  onUploadFile: function (successCallback) {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'], // 图片压缩类型
      sourceType: ['album', 'camera'],
      success: (chooseResult) => {
        const tempFilePath = chooseResult.tempFilePaths[0];
        // 上传图片到服务器
        wx.uploadFile({
          url: api.uploadFile,
          filePath: tempFilePath, // 本地文件路径
          name: 'file',
          success: (uploadResult) => {
            const data = JSON.parse(uploadResult.data);
            console.log('上传文件结果');
            console.log(data);
            if (data.code === 200) {
              wx.showToast({
                title: '上传成功',
                icon: 'success'
              });
              // 执行上传成功后的回调
              if (typeof successCallback === 'function') {
                successCallback(data.data);
              }
            } else {
              wx.showToast({
                title: '上传失败1',
                icon: 'none'
              });
            }
          },
          fail: (error) => {
            console.log(error);
            wx.showToast({
              title: '上传失败2',
              icon: 'none'
            });
          }
        });
      },
      fail: () => {
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },
  splitImageUrlsBy() {
    const {
      customerLicense
    } = this.data.customerInfo;
    if (customerLicense) {
      var pic = [];
      if (customerLicense.includes('&&')) {
        // 使用逗号切割字符串
        pic = customerLicense.split('&&');
      } else {
        // 如果没有逗号，则直接将 customerLicense 放入 pic 数组中
        pic = [customerLicense];
      }
      console.log('切割之后的数组', pic);
      this.setData({
        ImgList: pic
      });
    }
  },

  onModifySuccess: function (e) {
    console.log(this.data.customerInfo)
    wx.request({
      url: api.updateCustomerInfo,
      method: 'POST',
      data: Object.assign({}, this.data.customerInfo), // 将 customerInfo 平铺
      success: (res) => {
        wx.hideLoading()
        console.log('修改信息结果', res.data)
        if (res.data.code == 200) {
          wx.showToast({
            title: "修改信息成功",
            icon: "none"
          })
        } else {
          console.log('上传失败')
          wx.showToast({
            title: res.data.mesage,
            icon: "none"
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.getStorage({
      key: 'psCustomerCode',
      success: (res) => {
        this.setData({
          'cusotmerInfo.customerCode': res.data
        });

        wx.request({
          url: api.customerInfo,
          method: 'POST',
          data: {
            customerCode: this.data.cusotmerInfo.customerCode, // 使用 data 中的值
          },
          success: (res) => {
            wx.hideLoading()
            if (res.data.code == 200) {
              console.log("我的信息：")
              console.log(res.data.data)
              this.setData({
                customerInfo: res.data.data
              })
              this.splitImageUrlsBy()
            } else {
              wx.showToast({
                title: res.data.mesage,
                icon: "none"
              })
            }
          }
        })
      },
    });
  },
  // 选择单位类别
  onSelectCategory: function (e) {
    const category = Number(e.currentTarget.dataset.category); // 将字符串转换为数字
    this.setData({
      'customerInfo.customerCategory': category // 使用字符串路径更新嵌套字段
    }, () => {
      console.log('Selected category updated to:', this.data.customerInfo.customerCategory);
    });
  },
})